<template>
 <div>
   <div class="search">
     <input
       class="search-input"
       :class="{'opacity-0': isShowPlace}"
       type="text"
       v-model="inputValue"
       @focus="focusHandler"
       @blur="blurHandler"
       />
     <div class="serch-place" v-show="isShowPlace">
       <span class="iconfont">&#xe60b;</span>
       <div class="serch-place-text">搜索城市</div>
     </div>
   </div>
   <ul class="list">
    <li v-for="item of machedCities" :key="item.id" class="row-button border-bottom">{{item.name}}</li>
   </ul>
 </div>
</template>

<script>
export default {
  name: 'CitySearch',
  props: {
    cityData: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      inputValue: '',
      inputState: false
    }
  },
  computed: {
    isShowPlace () {
      return this.inputValue.length === 0 && !this.inputState
    },
    cities () {
      const cities_ = this.cityData.cities
      let cities = []
      for (let letter in cities_) {
        cities = cities.concat(cities_[letter])
      }
      return cities
    },
    machedCities () {
      let machedCities = []
      if (this.inputValue) {
        for (let city of this.cities) {
          if (city.spell.indexOf(this.inputValue) !== -1 ||
            city.name.indexOf(this.inputValue) !== -1) {
            machedCities.push(city)
          }
        }
      }
      this.$emit('searchChange', machedCities.length === 0)
      return machedCities
    }
  },
  methods: {
    focusHandler () {
      this.inputState = true
    },
    blurHandler () {
      this.inputState = false
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/variables.styl'
.border-bottom
  &:before
    border-color: #ccc
.search
  position: relative
  height: .6rem
  line-height: .6rem
  background: $bgColor
  padding .1rem .2rem
  z-index: 0
  .search-input
    position: relative
    box-sizing: border-box
    width: 100%
    height: 100%
    border-radius: .1rem
    padding 0 .1rem
    z-index: 2
  .serch-place
    position: absolute
    top: .1rem
    left: .2rem
    right: .2rem
    bottom: .1rem
    background: #fff
    border-radius: .1rem
    padding-left: .1rem
    z-index: 1
    .serch-place-text
      position: absolute
      top: 0
      left: 0
      right: 0
      bottom: 0
      color: #ccc
      text-align: center
  .opacity-0
    opacity: 0
.row-button
  overflow: hidden
  white-space: nowrap
  text-overflow: ellipsis
  line-height: .76rem
  height: .76rem
  padding-left: .2rem
</style>
